import sys
import random
import matplotlib
import os
import matplotlib
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QVBoxLayout, QSizePolicy, QScrollArea, QFrame, QAbstractScrollArea, QWidget
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QIcon, QPixmap
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import numpy as np
from utils.log_util import loggings

matplotlib.use("Qt5Agg")
plt.style.use('fivethirtyeight')
plt.rcParams['figure.constrained_layout.use'] = True


# QDockWidget可放大缩小的窗口
# 调用方法实例化PlotWindow类
# 画图时调取该对象得self.sc接口 也就是MyMplCanvas类的函数


class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def __init__(self, parent=None, width=5, height=4, dpi=500, title='', ):
        self.title = title
        self.tool_bar = None
        self.fig = plt.figure(figsize=(width, height), facecolor="#E4E4E4", dpi=dpi, constrained_layout=True)
        self.axes = self.fig.add_subplot(1, 1, 1)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        self.axes_list = []
        self.curveObj = None
        self.show_log = False
        self.y_invert = False

    def UpdatePlot(self):
        self.draw()

    def clear(self):
        # plt.cla()
        self.axes.clear()
        self.axes.grid()
        self.UpdatePlot()

    def _clear_plot(self):
        for axes in self.axes_list:
            axes.remove()
        self.UpdatePlot()

    def plot(self, datax, datay,title,x_label,y_label, line_color="r"):
        try:
            self.clear()
            if self.curveObj is None:
                # create draw object once
                if self.show_log:
                    self.axes.set_yscale("log")
                    # self.axes.invert_xaxis()
                if self.y_invert:
                    self.axes.invert_yaxis()
                self.axes.grid()
                # self.curveObj, = self.axes.plot(np.array(datax), np.array(datay), line_color)
                self.axes.set_title(title)
                self.axes.set_xlabel(x_label)
                self.axes.set_ylabel(y_label)
                self.curveObj, = self.axes.plot(datax, datay, line_color)
            # self.curveObj, = self.axes.plot(np.array(datax), np.array(datay), 'yo-')
            else:
                
                # update dataHandle of draw object
                # self.axes.plot(datax, datay, line_color)
                if self.show_log:
                    self.axes.set_yscale("log")
                    # self.axes.invert_xaxis()
                if self.y_invert:
                    self.axes.invert_yaxis()
                self.axes.grid()
                self.axes.set_title(title)
                self.axes.set_xlabel(x_label)
                self.axes.set_ylabel(y_label)
                # self.axes.plot(np.array(datax), np.array(datay), line_color)
                self.axes.plot(datax, datay, line_color)
            self.UpdatePlot()
        except Exception as e:
            loggings.error("plot" + str(e))

    def plot_data(self, result_dict):
        label_len = len(result_dict)
        if label_len % 2 != 0:
            row_count = int(label_len / 2) + 1
        else:
            row_count = int(label_len / 2)
        plot_id = 1
        self.axes_list = []
        for title_mode in result_dict:
            axes = plt.subplot(row_count, 2, plot_id)
            plt.title(title_mode)
            axes.grid()
            axes.hist(result_dict[title_mode])
            plot_id += 1
            self.axes_list.append(axes)
        self.UpdatePlot()


# customize navigation toolbar
class NavToolbar(NavigationToolbar):
    def __init__(self, canvas, parent):
        self.canvas = canvas
        super().__init__(canvas, parent, False)

    def save_img(self, path):
        # print("path", path)
        self.canvas.print_figure(path, format='png')


class PlotWindow(QWidget):
    def __init__(self):
        super(PlotWindow, self).__init__()
        icon = QIcon()
        icon.addPixmap(
            QPixmap("./icons/new_logo.ico"),
            QIcon.Normal,
            QIcon.Off)
        self.setWindowIcon(icon)
        # with open("./static/style_sheet/origin.qss", 'r') as f:
        #     self.setStyleSheet(f.read())
        self.setWindowTitle("HisunTest System")
        self.vl_content = QVBoxLayout(self)
        self.sa_content = QScrollArea()
        self.sa_content.setFrameShape(QFrame.NoFrame)
        sizePolicy = QSizePolicy(
            QSizePolicy.Expanding,
            QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(10)
        sizePolicy.setHeightForWidth(
            self.sa_content.sizePolicy().hasHeightForWidth())
        self.sa_content.setSizePolicy(sizePolicy)
        self.sa_content.setMinimumSize(QSize(0, 0))
        self.sa_content.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)
        self.sa_content.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.sa_content.setWidgetResizable(True)
        self.wd_sa_content = QWidget()
        self.vl_sa_content = QVBoxLayout(self.wd_sa_content)
        self.cv_plot = MyMplCanvas(self, width=5, height=4, dpi=100)
        self.cv_tool = NavToolbar(self.cv_plot, self)  # full toolbar
        self.cv_plot.tool_bar = self.cv_tool
        self.vl_sa_content.addWidget(self.cv_tool)
        self.vl_sa_content.addWidget(self.cv_plot)
        self.sa_content.setWidget(self.wd_sa_content)
        self.vl_content.addWidget(self.sa_content)

    def _setAutoHeight(self, count):
        self.wd_sa_content.setMinimumHeight(count * 250)
